/*
 * DprLockManager.h
 *
 *  Created on: 2012-11-26
 *      Author: kylin
 */

#ifndef DPRLOCKMANAGER_H_
#define DPRLOCKMANAGER_H_

#include <QObject>
#include <QMutex>
#include <QMap>
#include "gtype.h"

typedef struct _tDprLockSwitchMap
{
	int lockAddr;
	int switchNum;
}DprLockSwitchMap;

class DprSwitch
{
public:
	DprSwitch(const QString &devNode);
	~DprSwitch();

public:
	bool init();
	void clear();

	bool opening(int switchNum);
	bool closing(int switchNum);

private:
	QString m_devNode;
	int m_fd;
};

enum DprLockType
{
	dltWiring=1,
	dltMain=2,
	dltLink=3,
};

class DprLock : public QObject
{
	Q_OBJECT
public:
	DprLock(int addr);
	~DprLock();

signals:
	void sigPowerDown(int addr);

public:
	int addr(){return m_addr;}

	bool lockWiring(){return m_wiringLock;}
	bool lockMain(){return m_mainLock;}
	bool lockLink(){return m_linkLock;}

	void updateLockWiring(bool state);
	void updateLockMain(bool state);
	void updateLockLink(bool state);

private:
	int m_addr;
	bool m_wiringLock;
	bool m_mainLock;
	bool m_linkLock;
};

class DprLockManager : public QObject
{
	Q_OBJECT
public:
	DprLockManager(const QString &switchDevNode);
	virtual ~DprLockManager();

signals:
	void sigAlarm(DprAlarmEvent event);
	void sigSoe(DprSoeEvent event);

public:
	RunningState runningState(){return m_rs;}
	void setRunningState(RunningState rs);

	bool init();
	void clear();

	bool lockState(unsigned short lockAddr,bool &state);
	bool updateLockState(unsigned short lockAddr,bool state);

	bool soeEvent(int index,DprSoeEvent &event);
	bool alarmEvent(int index,DprAlarmEvent &event);

	void testOutput(int switchNum);

protected slots:
	void powerDown(int index);

private:
	int lockIndex(unsigned short lockAddr,DprLockType &type);

private:
	QMutex m_mutex;
	QList<DprLock*> m_locks;
	DprSwitch* m_switch;

	// These three maps connects the address of the lock and its index.
	QMap<unsigned short,int> m_wiringLockAddrMap;
	QMap<unsigned short,int> m_mainLockAddrMap;
	QMap<unsigned short,int> m_linkLockAddrMap;

	// This map connects the lock and the switch,key=lock index,
	// value = switch serial number.
	QMap<int,int> m_lockSwitchMap;

	QList<DprSoeEvent*> m_lstSoe;
	QList<DprAlarmEvent*> m_lstAlarm;

	QString m_switchDevNode;

	RunningState m_rs;
};

#endif /* DPRLOCKMANAGER_H_ */
